package utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import utils.BlueUtils2.Callbacks2;
import bean.BlueBean;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.widget.Toast;

public class BlueUtils3 {

	private static BlueUtils2 blueUtils;
	private Context mContext;
	private ArrayList<BluetoothDevice> mBlueList;
	private BluetoothAdapter mBluetoothAdapter;
	private Callbacks3 callback3;
	private LocationManager locationManager;

	// 单例模式
	public static BlueUtils2 getBlueUtils() {
		if (blueUtils == null) {
			blueUtils = new BlueUtils2();
		}
		return blueUtils;
	}


	//初始化
	public void getInit(Context context){
		this.mContext = context;
		//device集合
		mBlueList = new ArrayList<BluetoothDevice>();
		//adpter
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		// 找到设备的广播
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        // 注册广播
        mContext.registerReceiver(receiver, filter);
        // 搜索完成的广播
        IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        // 注册广播
        mContext.registerReceiver(receiver, filter1);
        
        try {
			Thread.sleep(1000);
			startScanBluth();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	// gps是否可用(有些设备可能需要定位)
	public boolean isGpsEnable(final Context context) {
		locationManager = (LocationManager) context
				.getSystemService(Context.LOCATION_SERVICE);
		boolean gps = locationManager
				.isProviderEnabled(LocationManager.GPS_PROVIDER);
		boolean network = locationManager
				.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
		if (gps || network) {
			return true;
		}
		return false;
	}

	// 判断是否支持蓝牙
	public boolean isSupportBlue() {
		if (!mContext.getPackageManager().hasSystemFeature(
				PackageManager.FEATURE_BLUETOOTH_LE)) {
			return true;
		} else {
			return false;
		}
	}
	
	//开始扫描
	private void startScanBluth() {
        // 判断是否在搜索,如果在搜索，就取消搜索
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
        // 开始搜索
        mBluetoothAdapter.startDiscovery();
        Toast.makeText(mContext, "开始扫描", 0).show();
    }
	
	//返回蓝牙对象
	public BluetoothAdapter getmBluetoothAdapter() {
		return mBluetoothAdapter;
	}
	//返回定位管理器
	public LocationManager getLocationManager(){
		return locationManager;
	}
	
	//扫描广播
	private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 收到的广播类型
            String action = intent.getAction();
            // 发现设备的广播
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // 从intent中获取设备
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // 是否配对
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    if (!mBlueList.contains(device)) {
                        mBlueList.add(device);
                        callback3.CallbackList(mBlueList);
                    }
                }
                // 搜索完成
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            	mContext.unregisterReceiver(receiver);
            	mBluetoothAdapter.cancelDiscovery();
            	Toast.makeText(mContext, "扫描完成", 0).show();
            }
        }
    };
    
    /**
	 * 接口回调
	 */
	public interface Callbacks3 {
		void CallbackList(List<BluetoothDevice> beanList);
	}

	/**
	 * 设置接口回调
	 */
	public void setCallback3(Callbacks3 callback3) {
		this.callback3 = callback3;
	}
	
	public String getBluetoothAddress() {
        try {
            BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            Field field = bluetoothAdapter.getClass().getDeclaredField("mService");
            // 参数值为true，禁用访问控制检查
            field.setAccessible(true);
            Object bluetoothManagerService = field.get(bluetoothAdapter);
            if (bluetoothManagerService == null) {
                return null;
            }
            Method method = bluetoothManagerService.getClass().getMethod("getAddress");
            Object address = method.invoke(bluetoothManagerService);
            if (address != null && address instanceof String) {
                return (String) address;
            } else {
                return null;
            }
            //抛一个总异常省的一堆代码...
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
